package com.dgj.kop.serverlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Strings;

import com.dgj.kop.common.SignUtil;

/**
 * KOP框架入口
 * 
 * @author Kerbores
 *
 */
public class KOPServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 默认的service调用入口
	 */
	public static String SERVICE_INVOKE_URL = "service";
	private static String CHARACTERENCODING;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		CHARACTERENCODING = config.getInitParameter("charset");
		if (CHARACTERENCODING == null) {
			CHARACTERENCODING = "UTF-8";// 默认编码 UTF-8
		}
		String serviceUrl = config.getInitParameter("service");
		if (!Strings.isBlank(serviceUrl)) {
			SERVICE_INVOKE_URL = serviceUrl;
		}
		if (!SERVICE_INVOKE_URL.startsWith("/")) {
			SERVICE_INVOKE_URL = "/" + SERVICE_INVOKE_URL;
		}
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 编码
		request.setCharacterEncoding(CHARACTERENCODING);
		response.setCharacterEncoding(CHARACTERENCODING);
		// 检查签名
		// boolean fileUpload = Strings.equals("1",
		// request.getHeader("fileUpload"));
		String appKey = request.getHeader("ak");
		String appSecret = request.getHeader("sk");
		String method = request.getHeader("method");
		String sign = request.getHeader("sign");
		String lengthKey = request.getHeader("length");
		String timestamp_ = request.getHeader("timestamp");
		if (!check(appKey, appSecret)) {
			ResponseUtils.responseException("非法的APPkey或者appSecret", request, response);
			return;
		}

		if (Strings.isBlank(lengthKey) || Strings.isBlank(timestamp_)) {
			ResponseUtils.responseException("非法调用:不符合参数传递规则", request, response);
			return;
		}
		int length = Integer.parseInt(lengthKey);
		if (!SignUtil.check(sign, method, appKey, appSecret, length)) {// 签名检查
			ResponseUtils.responseException("非法调用:签名不合法", request, response);
			return;
		}
		// 获取request中的method参数作为调用url
		if (Strings.isBlank(method)) { // URL校验
			ResponseUtils.responseException("调用method不能为空", request, response);
			return;
		}
		double timestamp = Double.parseDouble(timestamp_);
		if (!checkTimeStamp(timestamp)) {
			ResponseUtils.responseException("过期的调用,请调整你的系统时间,当前系统时间戳为" + System.currentTimeMillis(), request, response);
			return;
		}

		// forward到指定地址
		request.getRequestDispatcher(SERVICE_INVOKE_URL + "/" + method).forward(request, response);
	}

	private boolean checkTimeStamp(double timestamp) {
		return true;
	}

	private boolean check(String appKey, String appSecret) {
		// TODO 验证.0

		return true;
	}
}
